package com.jiayou.im.controller

import cn.hutool.core.io.FileUtil
import cn.hutool.core.io.IoUtil
import cn.hutool.core.util.ClassUtil
import cn.hutool.core.util.RandomUtil
import cn.hutool.system.UserInfo
import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
import com.jiayou.im.entity.Userinfo
import com.jiayou.im.service.impl.UserinfoServiceImpl
import com.jiayou.im.vo.Resoult
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.FileOutputStream
import javax.servlet.http.HttpServletResponse

/**
 *
 *
 * 前端控制器
 *
 *
 * @author lishuang
 * @since 2020-11-20
 */
@RestController
@RequestMapping("/im/userinfo")
open class UserinfoController {


    @Value("${'$'}{img.url}")
    private lateinit var PATH: String

    @Autowired
    private lateinit var userinfoServiceImpl: UserinfoServiceImpl


    //获取用户信息
    @RequestMapping("getUserInfo")
    open fun getUserInfo(@RequestParam("username") username: String) =
        Resoult(200, userinfoServiceImpl.getById(username))


    //更新昵称
    @Transactional
    @PostMapping("updatePetname")
    open fun updatePetname(
        @RequestParam("username") username: String,
        @RequestParam("petname") petname: String
    ): Resoult<String> {
        return if (userinfoServiceImpl.update(
                KtUpdateWrapper(Userinfo::class.java).eq(Userinfo::username, username)
                    .set(Userinfo::petname, petname)
            )
        ) {
            Resoult.success("更新成功！")
        } else
            Resoult.fail("更新失败！")
    }

    //更新性别
    @Transactional
    @PostMapping("updateGender")
    open fun updateGender(
        @RequestParam("username") username: String,
        @RequestParam("gender") gender: Int
    ): Resoult<String> {
        return if (userinfoServiceImpl.update(
                KtUpdateWrapper(Userinfo::class.java).eq(Userinfo::username, username)
                    .set(Userinfo::gender, gender)
            )
        ) {
            Resoult.success("更新成功！")
        } else
            Resoult.fail("更新失败！")
    }


    //更新个性签名
    @Transactional
    @PostMapping("updateDescription")
    open fun updateDescription(
        @RequestParam("username") username: String,
        @RequestParam("description") description: String
    ): Resoult<String> {
        return if (userinfoServiceImpl.update(
                KtUpdateWrapper(Userinfo::class.java).eq(Userinfo::username, username)
                    .set(Userinfo::description, description)
            )
        ) {
            Resoult.success("更新成功！")
        } else
            Resoult.fail("更新失败！")
    }


    //获取头像（根据头像文件名）
    @RequestMapping("getImgByName")
    open fun getImg1(@RequestParam("img") img: String, httpServletResponse: HttpServletResponse) {
        httpServletResponse.status = 200
        httpServletResponse.contentType = "image/jpeg"
        httpServletResponse.outputStream.write(FileUtil.file("$PATH/$img").readBytes())
        httpServletResponse.outputStream.close()
    }

    //获取头像（根据id）
    @RequestMapping("getImgById")
    open fun getImg2(@RequestParam("id") id: String, httpServletResponse: HttpServletResponse) {
        httpServletResponse.status = 200
        httpServletResponse.contentType = "image/jpeg"
        httpServletResponse.outputStream.write(
            FileUtil.file("$PATH/${userinfoServiceImpl.getById(id)?.img}").readBytes()
        )
        httpServletResponse.outputStream.close()
    }


    //修改头像
    @PostMapping("updateImg")
    open fun updateImg(@RequestParam("id") id: Int, @RequestParam("img") img: MultipartFile): Resoult<String> {
        if (img.size > 1024 * 1024)
            return Resoult.fail("图片太大啦！")

        val last = img.originalFilename?.split(".")?.last()
        return if (last == "jpg" || last == "png") {
            val fileName = RandomUtil.randomString(10) + img.originalFilename
            val fileOutputStream = FileOutputStream("$PATH/$fileName")
            IoUtil.copy(img.inputStream, fileOutputStream)
            img.inputStream.close()
            fileOutputStream.flush()
            fileOutputStream.close()
            userinfoServiceImpl.update(
                KtUpdateWrapper(Userinfo::class.java)
                    .eq(Userinfo::username, id)
                    .set(Userinfo::img, fileName)
            )
            Resoult.success(fileName)
        } else
            Resoult.fail("上传失败！")
    }

}
